package com.boot.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boot.constants.RedisKeys;
import com.boot.entity.ImageInfo;
import com.boot.entity.User;
import com.boot.service.IImageInfoService;
import com.boot.service.IUserService;
import com.boot.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务：扫描新上传的图片并通知管理员
 */
@Slf4j
@Component
public class ImageUploadNotificationTask {

    @Resource
    private IImageInfoService imageInfoService;

    @Resource
    private IUserService userService;

    @Resource
    private MailService mailService;

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String adminEmail;

    /**
     * 每隔 2 分钟执行一次扫描
     */
    @Scheduled(fixedDelay = 2_000) // 120秒 = 2分钟
    public void scanAndNotifyNewImageUploads() {
        log.info("[定时任务] 开始扫描新上传的图片...");

        try {
            LocalDateTime twoMonthAgo = LocalDateTime.now().minusMonths(2);

            QueryWrapper<ImageInfo> wrapper = new QueryWrapper<>();
            wrapper.gt("created_at", twoMonthAgo)
                    .eq("status", "approved"); // 只处理已通过状态的图片

            List<ImageInfo> newImages = imageInfoService.list(wrapper);
            log.info("找到 {} 张近2个月内上传的新图片", newImages.size());

            for (ImageInfo image : newImages) {
                String imageIdKey = String.valueOf(image.getId());

                // 检查是否已经发过通知
                Boolean hasNotified = redisTemplate.opsForSet().isMember(RedisKeys.SENT_IMAGE_NOTIFY, imageIdKey);
                if (Boolean.TRUE.equals(hasNotified)) {
                    continue;
                }

                try {
                    User uploader = userService.getById(image.getUserId());
                    String username = uploader != null ? uploader.getUsername() : "未知用户";

                    sendImageUploadNotification(username, image.getImageName(), image.getStoragePath());
                    log.info("✅ 已发送图片上传通知，图片ID={}", image.getId());

                    // 标记为已通知
                    redisTemplate.opsForSet().add(RedisKeys.SENT_IMAGE_NOTIFY, imageIdKey);
                } catch (Exception e) {
                    log.error("📧 发送图片上传通知失败（图片ID={}）: {}", image.getId(), e.getMessage(), e);
                }
            }
        } catch (Exception e) {
            log.error("【图片上传通知任务异常】", e);
        }
    }

    /**
     * 发送图片上传提醒邮件给管理员
     */
    private void sendImageUploadNotification(String username, String imageName, String storagePath) {
        try {
            String subject = "📸 新图片上传通知";
            String content = buildEmailContent(username, imageName, storagePath);
            mailService.sendHtmlMail(adminEmail, subject, content);
        } catch (Exception e) {
            log.error("邮件发送失败: " + e.getMessage(), e);
            throw new RuntimeException("邮件发送失败", e);
        }
    }

    /**
     * 构建邮件内容
     */
    private String buildEmailContent(String username, String imageName, String storagePath) {
        return "<div style='font-family: Arial, sans-serif; padding: 20px; border-radius: 8px; max-width: 600px; margin: auto; background: #f9f9f9;'>"
                    + "<h2 style='color: #1976D2;'>📸 新图片上传通知</h2>"
                    + "<p><strong>管理员您好：</strong></p>"
                    + "<p>有用户上传了新的图片，具体信息如下：</p>"
                    + "<table style='width:100%; border-collapse: collapse; margin: 20px 0;'>"
                        + "<tr><td style='padding: 8px; border: 1px solid #ddd; width: 30%;'><strong>上传用户</strong></td><td style='padding: 8px; border: 1px solid #ddd;'>" + escapeHtml(username) + "</td></tr>"
                        + "<tr><td style='padding: 8px; border: 1px solid #ddd;'><strong>图片名称</strong></td><td style='padding: 8px; border: 1px solid #ddd;'>" + escapeHtml(imageName) + "</td></tr>"
                        + "<tr><td style='padding: 8px; border: 1px solid #ddd;'><strong>存储路径</strong></td><td style='padding: 8px; border: 1px solid #ddd; font-size: 12px; color: #555;'>" + escapeHtml(storagePath) + "</td></tr>"
                    + "</table>"
                    + "<footer style='margin-top: 30px; color: #777; font-size: 0.9em; text-align: center;'>"
                    + "&copy; " + java.time.LocalDate.now().getYear() + " 系统管理平台</footer>"
                + "</div>";
    }

    private String escapeHtml(String str) {
        if (str == null) return "";
        return str.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#x27;");
    }
}
